import { _decorator, Component, Node } from 'cc';
import { Global } from '../../../script/Global';
import { RoomProto } from '../../room/script/RoomProto';
import { ICS_ROOM_ENTER, ISC_ROOM_ENTER } from 'db://assets/proto/proto';
import { show_hint, start_loading } from 'db://assets/sgame/ui/SUI';
import { RoomConst, RoomHint } from '../../room/script/RoomConst';
import { SceneManager } from 'db://assets/script/scene/SceneManager';
const { ccclass, property } = _decorator;

@ccclass('EnterPanel')
export class EnterPanel extends Component {
    private boardNumNode: Node;

    private numChars: string[] = [];

    private static MAX_NUM_LENGTH: number = 6;

    protected onLoad(): void {
        this.boardNumNode = this.node.Child("board/num");
    }

    start() {
        let keyboardNode: Node = this.node.Child("keyboard");
        let numSample: Node = keyboardNode.Child("sample");
        for (let i = 1; i <= 10; i++) {
            let numNode: Node = numSample.Copy(keyboardNode);
            let num = (i % 10).toString();
            numNode.LabelChild("num", num);
            numNode.OnClick(() => {
                this.numChars.push(num);
                if (this.numChars.length > EnterPanel.MAX_NUM_LENGTH) {
                    this.numChars.shift();
                }

                this.setBoardNum();
            });

            numNode.active = true;
        }

        let delNode: Node = numSample.Copy(keyboardNode);
        delNode.LabelChild("num", "删除");
        delNode.active = true;
        delNode.OnClick(() => {
            this.numChars.pop();
            this.setBoardNum();
        });

        let clearNode: Node = numSample.Copy(keyboardNode);
        clearNode.LabelChild("num", "清空");
        clearNode.active = true;
        clearNode.OnClick(() => {
            this.numChars = [];
            this.setBoardNum();
        });

        this.node.OnClickChild("enter", () => {
            const roomNum: number = parseInt(this.numChars.join(""));
            let params: ICS_ROOM_ENTER = {
                roomId: roomNum
            }

            Global.gameSocket.request(RoomProto.ROOM_ENTER, params, (result: ISC_ROOM_ENTER) => {
                if (result.code != RoomConst.CREATE_RESULT_CODE.SUCCESS) {
                    show_hint(`进入失败, ${RoomHint.ENTER_RESUT[result.code]}`);
                    return;
                }

                show_hint(`进入成功, ${RoomHint.ENTER_RESUT[result.code]}`);
                SceneManager.instance().enter("wzq");
            });
        })
    }

    setBoardNum() {
        this.boardNumNode.Label(this.numChars.join("  "));
    }
}
